import selectors
import socket
import logging

FORMAT = "%(asctime)s %(processName)s %(process)s %(threadName)s %(thread)s %(message)s"
logging.basicConfig(level=logging.INFO,format=FORMAT,datefmt='%Y%m%d-%H:%M:%S')


class HttpServer:
    def __init__(self,ip='127.0.0.1',port=80):
        self.server = socket.socket()
        self.addr = ip,port
        self.selector = selectors.DefaultSelector()
        # self.html = '<h1>Hello World!<h1>'.encode("utf-8")
        self.html = 'httpserver.html'

    def start(self):
        self.server.bind(self.addr)
        self.server.listen()
        self.key = self.selector.register(self.server, selectors.EVENT_READ, self.__accept)
        logging.info(self.key)

        while True:
            events = self.selector.select()
            for key, mask in events:
                # logging.info(key)
                key.data(key.fileobj, mask)

    def __accept(self,sock:socket.socket,mask):
        conn,raddr = sock.accept()
        conn.setblocking(False)

        newkey = self.selector.register(conn, selectors.EVENT_READ, self.__recv)
        logging.info(newkey)

    def __recv(self,clientsock:socket.socket,mask):
        try:
            data = clientsock.recv(1024)
            # print(data,type(data))
            with open(self.html,'rb') as f:
                clientsock.send(f.read())
            self.selector.unregister(clientsock)
            clientsock.close()
        except Exception as e:
            self.selector.unregister(clientsock)
            clientsock.close()
            logging.error(e)

web = HttpServer()
web.start()
